package seu.xml.validator;

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;

import javax.swing.*;

import scenario.ScenarioEvaluate;
import scenario.Stimulus;
import seu.architecture.simulation.SimulationWindowSwing;
import seu.evaluation.metric.MetricMainFrame;
import seu.verification.byspin.VerificationBySpin;
import seu.xml.validator.ArchitectureMetaModel.UMLetDiagram;

public class ValidationFrame extends JFrame implements ActionListener,
		ItemListener {
	private static final long serialVersionUID = 1L;
	private JComboBox combobox;
	JTextField textField = new JTextField("点击<选择文件>按钮");;
	private JButton button_choose = new JButton("选择文件"),
			button_match = new JButton("识别"),
			button_check = new JButton("图形检验"),
			button_add = new JButton("输入文件"), button_addAll = new JButton(
					"批量输入文件"), button_clear = new JButton("清除所有输入"),
			button_verify = new JButton("输入检验"), button_show = new JButton(
					"显示输入文件"), button_evaluation = new JButton(
					"<html>场景评估<br>子系统</html>"), button_metric = new JButton(
					"<html>属性度量<br>子系统</html>"),
			button_simulation = new JButton("<html>架构仿真<br>子系统</html>"),
			button_formal = new JButton("<html>形式验证<br>子系统</html>"),
			button_composite = new JButton("综合评价系统");
	private JLabel _type = new JLabel("选择文件类型", JLabel.CENTER);
	private static ValidationFrame frame;
	private static String _fileName;
	private ButtonGroup bg = new ButtonGroup();
	private JRadioButton langChi, langEng;
	private static int langType = 0;

	private static String notify1 = "检验通过";
	private static String notify2 = "检验失败，缺乏：";
	private static String notify3 = "文件不存在";
	private static String notify4 = "文件已输入";
	private static String notify5 = "输入成功";
	private static String notify6 = "无输入，无法评估";
	private static String notify7 = "未输入组件图，无法度量";
	private static String notify8 = "清除成功";
	private static String notify9 = "输入文件：";

	private static String type1 = "错误";
	private static String type2 = "通知";
	private static String type3 = "检验结果";

	public static int getLang() {
		return langType;
	}

	public static ValidationFrame getFrame() {
		if (frame == null)
			frame = new ValidationFrame();
		return frame;
	}

	private void refresh() {
		if (langType == 0)
			refresh0();
		else if (langType == 1)
			refresh1();
	}

	private void refresh1() {
		this.setTitle("Architecture Verification");
		button_choose.setText("Choose File");
		button_match.setText("Get Type");
		button_check.setText("Check File");
		button_add.setText("Input");
		button_addAll.setText("Input Folder");
		button_clear.setText("Clear Input");
		button_verify.setText("Test Input");
		button_show.setText("Show Inputed Files");
		button_evaluation.setText("Evaluate");
		button_metric.setText("Metric");
		button_simulation.setText("Simulate");
		button_formal.setText("Verify");
		button_composite.setText("Summery");
		textField.setText("click the button choose file");
		_type.setText("choose type");

		combobox.removeAllItems();
		UMLetDiagram[] ds = UMLetDiagram.values();
		Object cja[] = new Object[ds.length];
		for (int i = 0; i < ds.length; i++)
			combobox.addItem(ds[i].getName());

		notify1 = "Test Passed";
		notify2 = "Test Failed, lack: ";
		notify3 = "File does not Exist";
		notify4 = "File Inputed";
		notify5 = "Inputed";
		notify6 = "No Input Diagrams to Evaluate";
		notify7 = "No Input Component Diagrams for Metrics";
		notify8 = "All Input Cleared";
		notify9 = "Input Files :";
		type1 = "ERROR";
		type2 = "Notice";
		type3 = "Result";
	}

	private void refresh0() {
		this.setTitle("架构检验");
		button_choose.setText("选择文件");
		button_match.setText("识别");
		button_check.setText("图形检验");
		button_add.setText("输入文件");
		button_addAll.setText("批量输入文件");
		button_clear.setText("清除所有输入");
		button_verify.setText("输入检验");
		button_show.setText("显示输入文件");
		button_evaluation.setText("<html>场景评估<br>子系统</html>");
		button_metric.setText("<html>属性度量<br>子系统</html>");
		button_simulation.setText("<html>架构仿真<br>子系统</html>");
		button_formal.setText("<html>形式验证<br>子系统</html>");
		button_composite.setText("综合评价系统");
		textField.setText("点击<选择文件>按钮");
		_type.setText("选择文件类型");

		combobox.removeAllItems();
		UMLetDiagram[] ds = UMLetDiagram.values();
		Object cja[] = new Object[ds.length];
		for (int i = 0; i < ds.length; i++)
			combobox.addItem(ds[i].getName());

		notify1 = "检验通过";
		notify2 = "检验失败，缺乏：";
		notify3 = "文件不存在";
		notify4 = "文件已输入";
		notify5 = "输入成功";
		notify6 = "无输入，无法评估";
		notify7 = "未输入组件图，无法度量";
		notify8 = "清除成功";
		notify9 = "输入文件：";
		type1 = "错误";
		type2 = "通知";
		type3 = "检验结果";
	}

	private ValidationFrame() {
		this.setTitle("架构检验");
		this.setSize(1000, 500);
		this.setLocation(500, 300);
		this.setLayout(new GridLayout(1, 1));
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);

		JPanel pan1 = new JPanel();
		pan1.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		c.insets = new Insets(20, 20, 20, 20);
		c.weightx = 0.2;
		c.weighty = 0.2;
		c.fill = GridBagConstraints.HORIZONTAL;
		this.add(pan1);

		button_choose.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser file = new JFileChooser();
				file.setCurrentDirectory(new File("D:/testcase/"));
				int result = file.showOpenDialog(new JPanel());
				if (result == JFileChooser.APPROVE_OPTION) {
					String fileName = file.getSelectedFile().getName();
					String dir = file.getCurrentDirectory().toString();
					String file_path = dir + "\\" + fileName;
					textField.setText(file_path);
					_fileName = fileName;
				}
			}
		});

		c.gridx = 0;
		c.gridy = 0;
		pan1.add(button_choose, c);

		// textField.setBackground(Color.ORANGE);
		textField.setActionCommand("textField");
		c.gridx = 1;
		c.gridy = 0;
		pan1.add(textField, c);

		button_match.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					File f = new File(textField.getText());
					ArrayList<ModelSpare> ret = ModelValidator.read(f);
					UMLetDiagram ad = UMLetDiagram.match(ret).get(0);
					combobox.setSelectedItem(ad.getName());
				} catch (Exception anything) {
					anything.printStackTrace();
				}
			}
		});
		c.gridx = 2;
		c.gridy = 0;
		pan1.add(button_match, c);

		// _type.setFont(new Font("微软雅黑",Font.PLAIN,16));
		_type.setAlignmentX(JLabel.CENTER_ALIGNMENT);
		c.gridx = 0;
		c.gridy = 1;
		pan1.add(_type, c);

		UMLetDiagram[] ds = UMLetDiagram.values();
		Object cja[] = new Object[ds.length];
		for (int i = 0; i < ds.length; i++)
			cja[i] = ds[i].getName();
		combobox.addItemListener(this);
		c.gridx = 1;
		c.gridy = 1;
		pan1.add(combobox, c);

		button_check.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					File f = new File(textField.getText());
					ArrayList<ModelSpare> ret = ModelValidator.read(f);
					String file_type = (String) combobox.getSelectedItem();
					UMLetDiagram tp = UMLetDiagram.getItem(file_type);
					ArrayList<ModelSpare> result = tp.check(ret);
					if (result.size() == 0)
						System.out.println(textField.getText() + notify1);
					else {
						System.out.print(textField.getText() + notify2);
						for (ModelSpare ms : result)
							System.out.print(ms + ", ");
						System.out.println();
					}
				} catch (Exception anything) {
					System.err.println(anything.toString());
				}
			}
		});
		c.gridx = 3;
		c.gridy = 0;
		pan1.add(button_check, c);

		button_add.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String file = textField.getText();
				if (!new File(file).exists()) {
					JOptionPane.showMessageDialog(null, notify3, type1,
							JOptionPane.ERROR_MESSAGE);
				} else if (GlobalCons.fileInputed(file)) {
					JOptionPane.showMessageDialog(null, notify4, type1,
							JOptionPane.ERROR_MESSAGE);
				} else {
					String type = (String) combobox.getSelectedItem();
					GlobalCons.set(file, _fileName, UMLetDiagram.getItem(type));
					JOptionPane.showMessageDialog(null, notify5, type2,
							JOptionPane.PLAIN_MESSAGE);
				}
			}
		});
		c.gridx = 2;
		c.gridy = 1;
		pan1.add(button_add, c);

		button_clear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				GlobalCons.init();
				JOptionPane.showMessageDialog(null, notify8, type2,
						JOptionPane.PLAIN_MESSAGE);
			}
		});
		c.gridx = 3;
		c.gridy = 1;
		pan1.add(button_clear, c);

		button_verify.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				StringBuffer message = new StringBuffer();
				for (int i = 0; i < GlobalCons.commet.length; i++) {
					String commmet = GlobalCons.getCommet(i);
					if (commmet == null)
						continue;
					if (GlobalCons.verify(i))
						message.append("√ ");
					else
						message.append("X ");
					message.append(GlobalCons.getCommet(i) + "\r\n");
				}
				JOptionPane.showMessageDialog(null, message.toString(), type3,
						JOptionPane.PLAIN_MESSAGE);
			}
		});
		c.gridx = 2;
		c.gridy = 2;
		pan1.add(button_verify, c);

		button_show.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				StringBuffer message = new StringBuffer();
				Integer num = 1;
				for (String file : GlobalCons.all_files.keySet()) {
					message.append(num.toString() + ". \t"
							+ GlobalCons.all_files.get(file).getName() + ": \t"
							+ file + "\n");
					num++;
				}
				JOptionPane.showMessageDialog(null, message.toString(),
						"已输入文件", JOptionPane.PLAIN_MESSAGE);
			}
		});
		c.gridx = 3;
		c.gridy = 2;
		pan1.add(button_show, c);

		button_evaluation.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 调用场景评估子系统
				if (GlobalCons.all_files.size() == 0) {
					JOptionPane.showMessageDialog(null, notify6, type2,
							JOptionPane.ERROR_MESSAGE);
				} else
					ScenarioEvaluate.main(null);
			}
		});
		c.gridx = 0;
		c.gridy = 3;
		pan1.add(button_evaluation, c);

		button_metric.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 调用属性度量子系统
				if (GlobalCons.cmpnDiagramPath.size() == 0) {
					JOptionPane.showMessageDialog(null, notify7, type2,
							JOptionPane.ERROR_MESSAGE);
				} else
					MetricMainFrame.getFrame();
			}
		});
		c.gridx = 1;
		c.gridy = 3;
		pan1.add(button_metric, c);

		button_simulation.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 调用架构仿真子系统
				EventQueue.invokeLater(new Runnable() {
					public void run() {
						try {
							SimulationWindowSwing window = new SimulationWindowSwing();
							if (window.jframe != null)
								window.jframe.setVisible(true);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			}
		});
		c.gridx = 2;
		c.gridy = 3;
		pan1.add(button_simulation, c);

		button_formal.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 调用形式验证子系统
				VerificationBySpin.main(null);
			}
		});
		c.gridx = 3;
		c.gridy = 3;
		pan1.add(button_formal, c);

		button_composite.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 调用综合评估系统
				JOptionPane.showMessageDialog(null, "未集成", type2,
						JOptionPane.WARNING_MESSAGE);
			}
		});
		c.gridx = 0;
		c.gridy = 2;
		//c.gridwidth = 2;
		pan1.add(button_composite, c);
		
		button_addAll.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser folder = new JFileChooser();
				folder.setCurrentDirectory(new File("D:/testcase/"));
				folder.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//只能选择目录
				int result = folder.showOpenDialog(new JPanel());
				if (result == JFileChooser.APPROVE_OPTION) {
					File file = folder.getSelectedFile();
					GlobalCons.input(file);
					JOptionPane.showMessageDialog(null, notify9+new Integer(GlobalCons.all_files.size()).toString(), type2,
							JOptionPane.PLAIN_MESSAGE);
				}				
			}
		});		
		c.gridx = 1;
		c.gridy = 2;
		pan1.add(button_addAll, c);

		langChi = new JRadioButton("中文", true);
		c.gridx = 1;
		c.gridy = 4;
		c.gridwidth = 1;
		langChi.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 设置为中文
				langType = 0;
				refresh();
			}
		});
		bg.add(langChi);
		pan1.add(langChi, c);
		langEng = new JRadioButton("English", false);
		c.gridx = 2;
		c.gridy = 4;
		langEng.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 设置为英文
				langType = 1;
				refresh();
			}
		});
		bg.add(langEng);
		pan1.add(langEng, c);

		// color
		button_evaluation.setBackground(Color.WHITE);
		button_metric.setBackground(Color.WHITE);
		button_simulation.setBackground(Color.WHITE);
		button_formal.setBackground(Color.WHITE);
		button_composite.setBackground(Color.yellow);

		this.setVisible(true);
	}

	@Override
	public void itemStateChanged(ItemEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub

	}

}
